package com.wzq.animal.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云文件存储工具类
 */
public class MyOSSUtils {
    private static String ENDPOINT = "oss-cn-hangzhou.aliyuncs.com";//外网访问节点
    private static String ACCESSKEYID = "LTAI5tNfPcjzqWQgvChtegop";//ACCESSKEYID
    private static String ACCESSKEYSECRET = "VxPOa2w0yLHUvY6I1cZNeRXI1sWi1X";//ACCESSKEYSECRET
    private static String BUCKETNAME = "sxanimals";//bucket 名称

    /**
     * 上传文件
     * @param file
     * @param location
     * @return
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file,String location) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT,ACCESSKEYID,ACCESSKEYSECRET);
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        originalFilename = uuid + originalFilename;
        originalFilename = location + "/" + originalFilename;
        ossClient.putObject(BUCKETNAME,originalFilename,inputStream);
        ossClient.shutdown();
        String url="https://"+BUCKETNAME+"."+ENDPOINT+"/"+originalFilename;
        return url;
    }

    /**
     * 删除文件
     * @param fileName 文件名（OSS 上的）
     */
    public static void delFile(String fileName){
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT,ACCESSKEYID,ACCESSKEYSECRET);
        OSSObject object = ossClient.getObject(BUCKETNAME, fileName);
        ossClient.shutdown();
    }


}
